<script setup lang='ts'>
import { ref, reactive } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import _ from 'lodash'
import { Search, Minus, Plus } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { useEnumStore } from "@/store/enumeration";
import useInstance from "@/hooks/useInstance";
import { useComListData } from "@/store/list"
import { EquityPortfolioSavePost } from "@/api/equity"
import { isValidInput } from "@/utils/validate"

defineOptions({
    name: "addPackage",
});


const { listCollect, getvirtualMemberList } = useComListData()
const ruleFormRef = ref<FormInstance>();


const {
    grantType,
    expiryPeriodType,
    packageUseType,
    schemeConfigletailsType
} = useEnumStore();
const emit = defineEmits(["refresh",'searchEdit']);
const { global } = useInstance();

const dialogBasic = ref({
    title: "新建组合配置",
    visible: false,
    width: 800,
    height: 300,
    showFooter: true,
    marginTop: "10vh",
})


// 如何设计 就是单独操作 最后在弄在一起 
const packageForm = reactive({
    portfolioName: null,// 组合名称
    equityType: 1,// 权益类型
    portfolioUsageMode: 2,// 权益组合配置项使用方式
    receiveUrl: null,// 领取链接
    // minusMoney: null,// 立减金额
    grantIntervalTime: null,// 发放间隔时间
    timeUnit: 2,// 发放间隔单位
    // firstGrantIntervalTime: null,//  首次发放间隔时间
    firstTimeUnit: 2,// 首次发放间隔单位
    monthGetNum: null,// 月领取数量
    singleGetNum: null,// 单次领取数量
    grantType: null,// 发放方式
    // firstGetNum: null,// 首次领取数量
    portfolioConfigList: [] as any,//  权益组合配置项列表
    reduceMoney: [{
        portfolioCode: null,//组合编码
        equityCode: null,//权益编码
        equityName: null,//权益名称
        equityType: null,//权益类型
    }] as any,//立减金
    ParkingVoucher: [{
        portfolioCode: null,//组合编码
        equityCode: null,//权益编码
        equityName: null,//权益名称
        equityType: null,//权益类型
    }] as any,//停车券 
    virtualMember: [{
        portfolioCode: null,//组合编码
        equityCode: null,//权益编码
        equityName: null,//权益名称
        equityType: null,//权益类型
    }] as any,//虚拟会员
})

const rules = reactive<FormRules>({
    portfolioUsageMode: [
        {
            required: true,
            trigger: "blur",
            message: "请选择使用方式",
        },
    ],
    equityType: [
        {
            required: true,
            trigger: "blur",
            message: "请选择权益分类",
        },
    ],
    grantType: [
        {
            required: true,
            trigger: "blur",
            message: "请选择发放方式",
        },
    ],
    singleGetNum: [
        {
            required: true,
            trigger: "blur",
            message: "请输入单次领取数量",
        },
    ],
    firstGetNum: [
        {
            required: true,
            trigger: "blur",
            message: "请输入首次领取数量",
        },
    ],
    monthGetNum: [
        {
            required: true,
            trigger: "blur",
            message: "请输入月领取数量",
        },
    ],
    firstGrantIntervalTime: [
        {
            required: true,
            trigger: "blur",
            message: "请输入首次发放间隔时间",
        },
    ],
    portfolioName: [
        {
            required: true,
            trigger: "blur",
            message: "请输入组合名称",
        },
        { validator: isValidInput, trigger: 'blur' }
    ],
    receiveUrl: [
        {
            required: true,
            trigger: "blur",
            message: "请输入领取链接",
        },
    ],
    grantIntervalTime: [
        {
            required: true,
            trigger: "blur",
            message: "请输入发放间隔时间",
        },
    ],
})
const equityChange = (e: any) => {
    console.log(e, 'ppp');
    // 数据要全部清空
    getvirtualMemberList({ equityVoucherType: e })

    packageForm.reduceMoney.length = 0
    packageForm.ParkingVoucher.length = 0
    packageForm.virtualMember.length = 0
    packageForm.reduceMoney.push({
        portfolioCode: null,//组合编码
        equityCode: null,//权益编码
        equityName: null,//权益名称
        equityType: null,//权益类型
    })
    packageForm.ParkingVoucher.push({
        portfolioCode: null,//组合编码
        equityCode: null,//权益编码
        equityName: null,//权益名称
        equityType: null,//权益类型
    })
    packageForm.virtualMember.push({
        portfolioCode: null,//组合编码
        equityCode: null,//权益编码
        equityName: null,//权益名称
        equityType: null,//权益类型
    })


}
const addReduceMoney = (type: number) => {
    if (type == 1) {
        packageForm.reduceMoney.push({
            portfolioCode: null,//组合编码
            equityCode: null,//权益编码
            equityName: null,//权益名称
            equityType: null,//权益类型
        })
    } else if (type == 2) {
        packageForm.virtualMember.push({
            portfolioCode: null,//组合编码
            equityCode: null,//权益编码
            equityName: null,//权益名称
            equityType: null,//权益类型
        })
    }

}
const lessReduceMoney = (item: any, type: number) => {
    if (type == 1) {
        const index = packageForm.reduceMoney.indexOf(item)
        if (index !== -1) {
            packageForm.reduceMoney.splice(index, 1)
        }
    } else if (type == 3) {
        const index = packageForm.virtualMember.indexOf(item)
        if (index !== -1) {
            packageForm.virtualMember.splice(index, 1)
        }
    }

}
//显示弹框
const show = (type: string, row?: any) => {
    dialogBasic.value.visible = true
    if (type == 'add') {
        const res = setAllKeysToNull(packageForm)
        getvirtualMemberList({ equityVoucherType: 1 })
        Object.assign(packageForm, res);
        packageForm.equityType = 1
        packageForm.portfolioUsageMode = 2
        packageForm.timeUnit = 2
        packageForm.firstTimeUnit = 2
        dialogBasic.value.title = '新增组合配置'
        packageForm.ParkingVoucher.length = 0
        packageForm.portfolioConfigList.length = 0
        packageForm.reduceMoney.length = 0
        packageForm.virtualMember.length = 0
        packageForm.reduceMoney.push({
            portfolioCode: null,//组合编码
            equityCode: null,//权益编码
            equityName: null,//权益名称
            equityType: null,//权益类型
        })
        packageForm.ParkingVoucher.push({
            portfolioCode: null,//组合编码
            equityCode: null,//权益编码
            equityName: null,//权益名称
            equityType: null,//权益类型
        })
        packageForm.virtualMember.push({
            portfolioCode: null,//组合编码
            equityCode: null,//权益编码
            equityName: null,//权益名称
            equityType: null,//权益类型
        })
    } else {
        dialogBasic.value.title = '编辑组合配置'
        Object.assign(packageForm, row)
        getvirtualMemberList({ equityVoucherType: packageForm.equityType })
        if (!packageForm.portfolioConfigList) packageForm.portfolioConfigList = []
        if (packageForm.equityType == 1) {
            Object.assign(packageForm.reduceMoney, row.portfolioConfigList)
        } else if (packageForm.equityType == 2) {
            Object.assign(packageForm.virtualMember, row.portfolioConfigList)
        } else {
            Object.assign(packageForm.ParkingVoucher, row.portfolioConfigList)
        }
    }
}


const resetForm = () => {
    ruleFormRef.value?.resetFields();
    ruleFormRef.value?.clearValidate()
};

const onClose = async () => {
    dialogBasic.value.visible = false

    // 怎么完美删除这些数据 
    packageForm.ParkingVoucher.length = 0
    packageForm.reduceMoney.length = 0
    packageForm.virtualMember.length = 0
    packageForm.portfolioConfigList.length = 0
    // packageForm.reduceMoney.splice(0,1)
    const res = await setAllKeysToNull(packageForm)
    Object.assign(packageForm, res);
    resetForm()
}

const onConfirm = async () => {

    console.log(packageForm);

    await ruleFormRef.value?.validate(async isOk => {
        if (isOk) {
            const arr = Object.assign({}, packageForm)
            console.log(arr);

            if (arr.portfolioConfigList) {
                arr.portfolioConfigList.length = 0
            } else {
                arr.portfolioConfigList = []
            }

            if (arr.equityType == 1) {
                arr.reduceMoney.forEach((it: any) => {
                    arr.portfolioConfigList.push(it)
                })
            } else if (arr.equityType == 2) {
                arr.virtualMember.forEach((it: any) => {
                    arr.portfolioConfigList.push(it)
                })
            } else {
                arr.ParkingVoucher.forEach((it: any) => {
                    arr.portfolioConfigList.push(it)
                })
            }
            delete arr.ParkingVoucher
            delete arr.virtualMember
            delete arr.reduceMoney
            const res = await EquityPortfolioSavePost(arr)
            if (res.code == 20000) {
                ElMessage({
                    type: "success",
                    message: packageForm.id ? "组合配置编辑成功" : "组合配置新增成功",
                });
                if(packageForm.id){
                    emit("searchEdit");

                }else{
                    emit("refresh");

                }
                onClose();
            }
        } else {
            ElMessage({
                type: "error",
                message: packageForm.id
                    ? "组合配置编辑失败 请重试！"
                    : "组合配置新增失败 请重试！",
            });
        }
    })
}
const reduceMoneySelect = (e: any, item: any, type: number) => {
    if (!e) {
        item.equityName = null
    } else {
        listCollect.virtualMemberList.forEach((it: any) => {
            console.log(it.key, it, e);

            if (it.key == e) {
                item.equityName = it.objName
            }
        })
    }
    console.log(item);


}
const setAllKeysToNull = (obj: any): any => {
    if (typeof obj !== 'object' || obj === null) {
        // 如果不是对象或已经是 null，则直接返回
        return obj;
    }

    if (Array.isArray(obj)) {
        // 如果是数组，则遍历每个元素
        return obj.map(item => setAllKeysToNull(item));
    }

    // 如果是普通对象，则遍历每个键值
    const newObj = {};
    for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
            const value = obj[key];

            if (typeof value === 'object' && value !== null) {
                // 如果是嵌套的对象，则递归处理
                newObj[key] = setAllKeysToNull(value);
            } else {
                // 否则设置为 null
                newObj[key] = null;
            }
        }
    }

    return newObj;
}

const changePortfolioUsageMode = (e: number) => {
    console.log(e);
    if (e == 2) {
        // 删除其他数据
        packageForm.reduceMoney && packageForm.reduceMoney.splice(1)
        packageForm.virtualMember && packageForm.virtualMember.splice(1)
    }
}

defineExpose({
    show
})
</script>

<template>
    <SysDialog :title="dialogBasic.title" :width="dialogBasic.width" :height="dialogBasic.height"
        :show-footer="dialogBasic.showFooter" :visible="dialogBasic.visible" :margin-top="dialogBasic.marginTop"
        @on-close="onClose" @on-confirm="onConfirm">
        <template v-slot:content>
            <div class="channel-form" v-loading="false">
                <el-form ref="ruleFormRef" :model="packageForm" :rules="rules" label-width="140px" class="demo-ruleForm"
                    status-icon>
                    <!--   status-icon -->
                    <el-form-item label="组合名称" prop="portfolioName">
                        <normal-input v-model:model-value="packageForm.portfolioName" maxlength="120"
                            show-word-limit></normal-input>
                    </el-form-item>
                    <el-form-item label="权益分类" prop="equityType">
                        <BlackSelect v-model:select-value="packageForm.equityType" @my-change="equityChange"
                            :clearable="false" :options="schemeConfigletailsType">
                        </BlackSelect>
                    </el-form-item>
                    <el-form-item label="使用方式" prop="portfolioUsageMode">
                        <BlackSelect v-model:select-value="packageForm.portfolioUsageMode" :disabled="!!packageForm.id"
                            @my-change="changePortfolioUsageMode" :clearable="false" :options="packageUseType">
                        </BlackSelect>
                    </el-form-item>
                    <el-form-item label="月领取数量" prop="monthGetNum">
                        <el-input-number v-model.number="packageForm.monthGetNum" clearable :min="1" :max="999"
                            style="width: 100%;" :controls="false" placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="发放间隔时间" prop="grantIntervalTime">
                        <el-input v-model="packageForm.grantIntervalTime" type="number"
                            @input="if (packageForm.grantIntervalTime > 127) packageForm.grantIntervalTime = 127; if (packageForm.grantIntervalTime < 0) packageForm.grantIntervalTime = 0;"
                            placeholder="发放间隔时间">
                            <template #append>
                                <BlackSelect style="width: 90px;" v-model:select-value="packageForm.timeUnit" disabled
                                    :options="expiryPeriodType"></BlackSelect>
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="单次领取数量" prop="singleGetNum">
                        <el-input-number v-model.number="packageForm.singleGetNum" clearable :min="1" :max="999"
                            style="width: 100%;" :controls="false" placeholder="请输入" />
                    </el-form-item>
                    <!-- <el-form-item label="首次领取数量" prop="firstGetNum">
                        <el-input-number v-model.number="packageForm.firstGetNum" clearable :min="0" :max="999"
                            style="width: 100%;" :controls="false" placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="首次发放间隔时间" prop="firstGrantIntervalTime">
                        <el-input v-model.number="packageForm.firstGrantIntervalTime" type="number"
                          @input="if (packageForm.firstGrantIntervalTime > 127) packageForm.firstGrantIntervalTime = 127; if (packageForm.firstGrantIntervalTime < 0) packageForm.firstGrantIntervalTime = 0;"
                            placeholder="首次发放间隔时间">
                            <template #append>
                                <BlackSelect style="width: 90px;" v-model:select-value="packageForm.firstTimeUnit"
                                    disabled :options="expiryPeriodType"></BlackSelect>
                            </template>
                        </el-input>
                    </el-form-item> -->

                    <el-form-item label="发放方式" prop="grantType">
                        <BlackSelect v-model:select-value="packageForm.grantType" :options="grantType">
                        </BlackSelect>
                    </el-form-item>
                    <el-form-item label="领取链接" prop="receiveUrl" v-if="packageForm.grantType == 2">
                        <normal-input v-model:model-value="packageForm.receiveUrl" maxlength="120"
                            show-word-limit></normal-input>
                    </el-form-item>
                    <template v-if="packageForm.equityType == 1">
                        <el-form-item v-for="(domain, index) in packageForm.reduceMoney" :key="domain.equityCode"
                            :label="`立减金  ${1 + index} `" :prop="'reduceMoney.' + index + '.equityCode'" :rules="{
                                required: true,
                                message: '请选择立减金',
                                trigger: 'change',
                            }">
                            <el-select filterable style="width: 520px; margin-right:10px" v-model="domain.equityCode"
                                @change="reduceMoneySelect($event, domain, 1)" placeholder="立减金" clearable>
                                <el-option v-for="item in listCollect.virtualMemberList" :key="item.id"
                                    :label="item.value" :value="item.key" />
                            </el-select>
                            <el-button type="danger" @click="lessReduceMoney(domain, 1)"
                                v-if="packageForm.reduceMoney.length > 1" :icon="Minus"> </el-button>
                        </el-form-item>
                        <el-form-item label="添加立减金" v-if="packageForm.portfolioUsageMode == 1">
                            <el-button type="primary" style="width: 100%;" @click="addReduceMoney(1)"
                                :icon="Plus"></el-button>
                        </el-form-item>
                    </template>
                    <template v-if="packageForm.equityType == 2">
                        <el-form-item v-for="(domain, index) in packageForm.virtualMember" :key="domain.equityCode"
                            :label="`虚拟会员  ${1 + index} `" :prop="'virtualMember.' + index + '.equityCode'" :rules="{
                                required: true,
                                message: '请选择虚拟会员',
                                trigger: 'change',
                            }">
                            <el-select filterable style="width: 520px; margin-right:10px" v-model="domain.equityCode"
                                @change="reduceMoneySelect($event, domain, 2)" placeholder="虚拟会员" clearable>
                                <el-option v-for="item in listCollect.virtualMemberList" :key="item.id"
                                    :label="item.value" :value="item.key" />
                            </el-select>
                            <el-button type="danger" @click="lessReduceMoney(domain, 3)"
                                v-if="packageForm.virtualMember.length > 1" :icon="Minus"> </el-button>
                        </el-form-item>
                        <el-form-item label="添加虚拟会员" v-if="packageForm.portfolioUsageMode == 1">
                            <el-button type="primary" style="width: 100%;" @click="addReduceMoney(2)"
                                :icon="Plus"></el-button>
                        </el-form-item>
                    </template>
                    <template v-if="packageForm.equityType == 3">
                        <el-form-item v-for="(domain, index) in packageForm.ParkingVoucher" :key="domain.equityCode"
                            label="停车券" :prop="'ParkingVoucher.' + index + '.equityCode'" :rules="{
                                required: true,
                                message: '请选择停车券',
                                trigger: 'change'
                            }">
                            <el-select filterable v-model="domain.equityCode"
                                @change="reduceMoneySelect($event, domain, 3)" placeholder="停车券" clearable>
                                <el-option v-for="item in listCollect.equityList" :key="item.id" :label="item.value"
                                    :value="item.key" />
                            </el-select>

                        </el-form-item>
                    </template>
                    <template v-if="packageForm.equityType == 4">
                        开发中
                    </template>


                </el-form>
            </div>
        </template>
    </SysDialog>
</template>

<style lang='scss' scoped>
.channel-form {
    height: 600px;
    overflow: auto;
}

:deep(.el-radio__inner) {
    border-radius: 2px !important;
}

:deep(.el-radio__input.is-checked .el-radio__inner::after) {
    content: '';
    width: 8px;
    height: 3px;
    border: 1px solid black;
    border-top: transparent;
    border-right: transparent;
    text-align: center;
    display: block;
    position: absolute;
    top: 3px;
    left: 2px;
    transform: rotate(-45deg);
    border-radius: 0px;
    background: none;
}

:deep(.el-select__suffix) {
    .el-input__validateIcon {
        display: none;
    }
}

:deep(.el-input-number .el-input__inner) {
    text-align: left;
}
</style>
